import java.sql.*;
import java.util.Scanner;

public class Login {
    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        Scanner scanner = new Scanner(System.in);
        int maxnum = 3;
        int num = 0;

        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;

        while (num < maxnum) {
            System.out.println("请输入用户名: ");
            String username = scanner.nextLine();
            System.out.println("请输入密码: ");
            String password = scanner.nextLine();

            try{
                //加载驱动
                Class.forName("com.mysql.jdbc.Driver");
                //获取数据库连接对象
                connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/servlet?useSSL=false","root","111111");
                //获取执行SQL语句的处理器
                statement = connection.createStatement();
                //执行SQL语句
                resultSet = statement.executeQuery("select * from user where username='"+username+"' and password='"+password+"'");
                //处理结果集
                if (resultSet.next()) {
                    System.out.println("登陆成功");
                    break;
                } else {
                    num++;
                    System.out.println("用户名或密码错误,还有" + (maxnum-num) + "次机会重新输入");
                    System.out.println();
                }
            }finally {
                //关闭资源
                if (connection != null) {
                    connection.close();
                }
                if (statement != null) {
                    statement.close();
                }
                if (resultSet != null) {
                    resultSet.close();
                }
            }
        }
        if (num >= maxnum) {
            System.out.println("输入次数到达上限,程序退出");
        }
    }
}